package com.bestcem.xm.openplatform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bestcem.xm.common.core.exception.BusinessException;
import com.bestcem.xm.common.core.uitls.StringUtil;
import com.bestcem.xm.component.mybatis.service.impl.XmServiceImpl;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.openplatform.controller.vo.*;
import com.bestcem.xm.openplatform.entity.*;
import com.bestcem.xm.openplatform.grpc.client.DeliverGrpcClient;
import com.bestcem.xm.openplatform.grpc.client.QdesGrpcClient;
import com.bestcem.xm.openplatform.grpc.client.dto.*;
import com.bestcem.xm.openplatform.mapper.*;
import com.bestcem.xm.openplatform.mq.dto.OpenplatformExtParamUpdateDto;
import com.bestcem.xm.openplatform.mq.send.biz.OpenplatformMessageSendService;
import com.bestcem.xm.openplatform.service.OpenplatformExtparamService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.bestcem.xm.deliver.grpc.v1.services.DeliverExtparamsStatus.DELIVEREXTPARAMS_STATUS_START;
import static com.bestcem.xm.deliver.grpc.v1.services.DeliverStatus.DELIVER_STATUS_DELETE;
import static com.bestcem.xm.deliver.grpc.v1.services.DeliverStatus.DELIVER_STATUS_FINISH;
import static com.bestcem.xm.openplatform.grpc.v1.services.EncryptionConfigEType.ENCRYPTIONCONFIG_E_TYPE_AES;
import static com.bestcem.xm.openplatform.grpc.v1.services.ExtParamEnumManageStatus.EXTPARAMENUMMANAGE_STATUS_DELETE;
import static com.bestcem.xm.openplatform.grpc.v1.services.ExtParamEnumManageStatus.EXTPARAMENUMMANAGE_STATUS_START;
import static com.bestcem.xm.openplatform.grpc.v1.services.ExtParamStatus.EXTPARAM_STATUS_DELETE;
import static com.bestcem.xm.openplatform.grpc.v1.services.ExtParamStatus.EXTPARAM_STATUS_START;

@Service
@Slf4j
@RequiredArgsConstructor
public class OpenplatformExtparamServiceImpl extends XmServiceImpl<OpenplatformExtparamMapper, OpenplatformExtparam> implements OpenplatformExtparamService {

    private @NonNull OpenplatformExtparamMapper openplatformExtparamMapper;
    private @NonNull OpenplatformEncryptionconfigMapper encryptionconfigMapper;
    private @NonNull OpenplatformSystemmanageMapper systemmanageMapper;
    private @NonNull OpenplatformConditionmanageMapper conditionmanageMapper;
    private @NonNull OpenplatformExtparamenummanageMapper extparamenummanageMapper;
    private @NonNull OpenplatformFunctionoptionMapper functionoptionMapper;

    private @NonNull DeliverGrpcClient deliverGrpcClient;
    private @NonNull QdesGrpcClient qdesGrpcClient;

    private @NonNull OpenplatformMessageSendService openplatformMessageSendService;

    @Override
    public OpenplatformExtparamVo getOpenplatformExtparamById(String extparamId) {
        OpenplatformExtparam openplatformExtparam = openplatformExtparamMapper.selectById(extparamId);
        OpenplatformExtparamVo openplatformExtparamVo = new OpenplatformExtparamVo();
        if (ObjectUtil.isNotEmpty(openplatformExtparam)) {
            BeanUtil.copyProperties(openplatformExtparam, openplatformExtparamVo);
            if (ObjectUtil.isEmpty(openplatformExtparamVo.getDescription())) {
                openplatformExtparamVo.setDescNme(openplatformExtparamVo.getName());
            } else {
                openplatformExtparamVo.setDescNme(openplatformExtparamVo.getDescription() + "|" + openplatformExtparamVo.getName());
            }
        }
        return openplatformExtparamVo;
    }

    @Override
    public List<OpenplatformExtparamVo> getOpenplatformExtparamList(HttpServletRequest request) {
        String orgId = SecurityContextHolder.getOrgId();
        List<OpenplatformExtparam> openplatformExtparams = openplatformExtparamMapper.selectList(new LambdaQueryWrapper<OpenplatformExtparam>()
                .eq(OpenplatformExtparam::getOrgId, orgId)
                .ne(OpenplatformExtparam::getStatus, EXTPARAM_STATUS_DELETE.getNumber()));
        List<OpenplatformExtparamVo> openplatformExtparamVos = new ArrayList<>();
        openplatformExtparams.forEach(a -> {
            OpenplatformExtparamVo openplatformExtparamVo = new OpenplatformExtparamVo();
            BeanUtil.copyProperties(a, openplatformExtparamVo);
            if (ObjectUtil.isEmpty(openplatformExtparamVo.getDescription())) {
                openplatformExtparamVo.setDescNme(openplatformExtparamVo.getName());
            } else {
                openplatformExtparamVo.setDescNme(openplatformExtparamVo.getDescription() + "|" + openplatformExtparamVo.getName());
            }
            openplatformExtparamVos.add(openplatformExtparamVo);
        });
        return openplatformExtparamVos;
    }

    @Override
    public OpenplatformExtparamPageVo getOpenplatformExtparamPage(Page<OpenplatformExtparam> page, HttpServletRequest request) {
        String orgId = SecurityContextHolder.getOrgId();
        OpenplatformExtparamPageVo pageVo = new OpenplatformExtparamPageVo();
        pageVo.setPage(page.getCurrent());
        Page<OpenplatformExtparam> openplatformExtparamPage = openplatformExtparamMapper.selectPage(page,
                new LambdaQueryWrapper<OpenplatformExtparam>().eq(OpenplatformExtparam::getOrgId, orgId).ne(OpenplatformExtparam::getStatus, EXTPARAM_STATUS_DELETE.getNumber()));
        List<OpenplatformExtparam> openplatformExtparams = openplatformExtparamPage.getRecords();
        if (CollUtil.isEmpty(openplatformExtparams)) {
            pageVo.setTotalCount(0);
            pageVo.setRows(new ArrayList<>());
            return pageVo;
        }
        List<OpenplatformExtparamVo> openplatformExtparamVos = new ArrayList<>();
        openplatformExtparams.forEach(a -> {
            OpenplatformExtparamVo openplatformExtparamVo = new OpenplatformExtparamVo();
            BeanUtil.copyProperties(a, openplatformExtparamVo);
            if (ObjectUtil.isEmpty(openplatformExtparamVo.getDescription())) {
                openplatformExtparamVo.setDescNme(openplatformExtparamVo.getName());
            } else {
                openplatformExtparamVo.setDescNme(openplatformExtparamVo.getDescription() + "|" + openplatformExtparamVo.getName());
            }
            openplatformExtparamVos.add(openplatformExtparamVo);
        });
        //组装
        pageVo.setRows(openplatformExtparamVos);
        pageVo.setTotalCount(openplatformExtparamPage.getTotal());
        return pageVo;
    }

    @Override
    @Transactional
    public Map<String, String> postOpenplatformExtparam(JSONObject param) {
        if (StringUtil.isNullOrEmpty(param.getString("name"))) {
            throw new BusinessException("缺少外部参数名称");
        }
        if (StringUtil.isNullOrEmpty(param.getString("desc"))) {
            throw new BusinessException("缺少外部参数描述");
        }
        if (!checkExtParamsNameFormat(param.getString("name"))) {
            throw new BusinessException("参数名称只能输入数字字母下划线，最多16字符, 不能以“xm_”开头");
        }
        if (checkExtParamsNameValid(param.getString("name"))) {
            throw new BusinessException("外部参数名称重复不可用");
        }
        if (!checkExtParamsNumByOrgId()) {
            throw new BusinessException("外部参数数量限制为100");
        }
        if (checkExtParamsDescValid(param.getString("desc"))) {
            throw new BusinessException("外部参数描述重复不可用");
        }
        if (!checkExtParamsDescFormat(param.getString("desc"))) {
            throw new BusinessException("参数描述不能以特殊字符开头，最多8个字符");
        }
        OpenplatformExtparam openplatformExtparam = new OpenplatformExtparam();
        openplatformExtparam.setName(param.getString("name"));
        openplatformExtparam.setDescription(param.getString("desc"));
        openplatformExtparam.setDtype(param.getInteger("dtype"));
        openplatformExtparam.setOrgId(SecurityContextHolder.getOrgId());
        openplatformExtparam.setStatus(0);
        Map<String, String> map = new HashMap<>();
        openplatformExtparamMapper.insert(openplatformExtparam);
        map.put("id", openplatformExtparam.getId());

        return map;

    }

    @Override
    public Map<String, String> putOpenplatformExtparam(String extparamId, JSONObject param) {
        //判断 oid 是否存在
        OpenplatformExtparam ext_param = openplatformExtparamMapper.selectById(extparamId);
        if (ObjectUtil.isEmpty(ext_param)) {
            throw new BusinessException("ExtParam[id={" + extparamId + "}] not found");
        }
        if (StringUtil.isNullOrEmpty(param.getString("desc"))) {
            throw new BusinessException("缺少外部参数描述");
        }
        if (!checkExtParamsNameFormat(param.getString("name"))) {
            throw new BusinessException("参数名称只能输入数字字母下划线，最多16字符, 不能以“xm_”开头");
        }
        if (!checkExtParamsNameValidPutMethod(extparamId, param.getString("name"))) {
            throw new BusinessException("外部参数名称重复不可用");
        }
        if (!checkExtParamsDescValidPutMethod(extparamId, param.getString("desc"))) {
            throw new BusinessException("外部参数描述重复不可用");
        }
        if (!checkExtParamsDescFormat(param.getString("desc"))) {
            throw new BusinessException("参数描述不能以特殊字符开头，最多8个字符");
        }
        updateExtparam(extparamId, param);

        //发送mq消息
        OpenplatformExtParamUpdateDto dto = new OpenplatformExtParamUpdateDto();
        dto.setExtParamId(extparamId);
        dto.setDesc(param.getString("desc"));
        openplatformMessageSendService.openplatformExtparamUpdateSend(dto);
        openplatformMessageSendService.openplatformDeliverSurveyExtVersionUpdateSend(dto);

        Map<String, String> map = new HashMap<>();
        map.put("id", extparamId);
        return map;
    }

    @Override
    public Map<String, Integer> deleteOpenplatformExtparam(String extparamId) {
        //判断 oid 是否存在
        OpenplatformExtparam ext_param = openplatformExtparamMapper.selectById(extparamId);
        if (ObjectUtil.isEmpty(ext_param)) {
            throw new BusinessException("ExtParam[id={" + extparamId + "}] not found");
        }
        Integer count = openplatformExtparamMapper.update(null, new LambdaUpdateWrapper<OpenplatformExtparam>()
                .eq(OpenplatformExtparam::getId, extparamId)
                .eq(OpenplatformExtparam::getOrgId, SecurityContextHolder.getOrgId())
                .set(OpenplatformExtparam::getStatus, EXTPARAMENUMMANAGE_STATUS_DELETE.getNumber()));
        Map<String, Integer> map = new HashMap<>();
        map.put("deletedCount", count);
        return map;
    }

    @Override
    public Map<String, Object> checkOpenplatformExtparam(String extparamId) {
        Map<String, Object> result = new HashMap<>();
        //判断 oid 是否存在
        OpenplatformExtparam ext_param = openplatformExtparamMapper.selectById(extparamId);
        if (ObjectUtil.isEmpty(ext_param)) {
            throw new BusinessException("ExtParam[id={" + extparamId + "}] not found");
        }
        JSONObject query = new JSONObject();
        query.put("org_id", SecurityContextHolder.getOrgId());
        query.put("extparam_id", extparamId);
        query.put("extparam_name", ext_param.getName());
        query.put("status", DELIVEREXTPARAMS_STATUS_START.getNumber());
        List<DeliverDto> deliverDtos = getDeliverExtParamsDetail(query);
        if (ObjectUtil.isNotEmpty(deliverDtos)) {
            List<Object> deliver_code_list = new ArrayList<>();
            deliverDtos.forEach(a -> deliver_code_list.add(a.getCode()));
            throw new BusinessException("编号为" + deliver_code_list + "的定制开发投放仍在使用此条件，暂不能删除，如需删除请先去修改配置或删除投放");
        }

        //判断是否有问卷在使用
        List<Object> survey_name = getSurveyExtParamsDetail(SecurityContextHolder.getOrgId(), extparamId);
        if (ObjectUtil.isNotEmpty(survey_name)) {
            throw new BusinessException("问卷中已经使用" + survey_name);
        }
        result.put("msg", "符合校验，可以删除");
        result.put("deletable", 1);
        return result;
    }

    @Override
    public OpenplatformEncryptionconfig getEncryptionConfigsById(String id) {
        return encryptionconfigMapper.selectById(id);
    }

    @Override
    public List<OpenplatformEncryptionconfig> getEncryptionConfigsList(HttpServletRequest request) {
        String orgId = request.getParameter("org_id");
        return encryptionconfigMapper.selectList(new LambdaQueryWrapper<OpenplatformEncryptionconfig>()
                .eq(OpenplatformEncryptionconfig::getOrgId, orgId));
    }

    @Override
    public OpenplatformEncryptionconfigPageVo getEncryptionConfigsPage(Page<OpenplatformEncryptionconfig> page, HttpServletRequest request) {
        String orgId = request.getParameter("org_id");
        OpenplatformEncryptionconfigPageVo pageVo = new OpenplatformEncryptionconfigPageVo();
        pageVo.setPage(page.getCurrent());
        Page<OpenplatformEncryptionconfig> encryptionconfigPage = encryptionconfigMapper.selectPage(page, new LambdaQueryWrapper<OpenplatformEncryptionconfig>()
                .eq(OpenplatformEncryptionconfig::getOrgId, orgId));
        List<OpenplatformEncryptionconfig> encryptionconfigList = encryptionconfigPage.getRecords();
        if (CollUtil.isEmpty(encryptionconfigList)) {
            pageVo.setTotalCount(0);
            pageVo.setRows(new ArrayList<>());
            return pageVo;
        }
        //组装
        pageVo.setRows(encryptionconfigList);
        pageVo.setTotalCount(encryptionconfigPage.getTotal());
        return pageVo;
    }

    @Override
    public Map<String, String> postSystemManages(JSONObject param) {
        checkSystemAndConditionCodeDesc(param);
        //判断系统编号是否可用
        if (!checkSystemCodeVlid(param, null)) {
            throw new BusinessException("编码重复不可用");
        }
        //判断业务含义是否重复
        if (!checkSystemDescValid(param, null)) {
            throw new BusinessException("system_no业务含义重复不可用");
        }
        //保存数据
        OpenplatformSystemmanage systemmanage = new OpenplatformSystemmanage();
        systemmanage.setOrgId(SecurityContextHolder.getOrgId());
        systemmanage.setCode(param.getString("code"));
        systemmanage.setDescription(param.getString("desc"));
        systemmanageMapper.insert(systemmanage);
        Map<String, String> map = new HashMap<>();
        map.put("id", systemmanage.getId());
        return map;
    }

    @Override
    public Map<String, String> putSystemManages(String id, JSONObject param) {
//        if (!systemmanageMapper.exists(new LambdaQueryWrapper<OpenplatformSystemmanage>()
//                .eq(OpenplatformSystemmanage::getId, id))) {
//            throw new BusinessException("CustomSystemManage[id=" + id + "}] not found");
//        }
        OpenplatformSystemmanage systemmanage = systemmanageMapper.selectById(id);
        if (ObjectUtil.isEmpty(systemmanage)) {
            throw new BusinessException("CustomSystemManage[id=" + id + "}] not found");
        }
        checkSystemAndConditionCodeDesc(param);
        //判断系统编号是否可用
        if (!checkSystemCodeVlid(param, id)) {
            throw new BusinessException("编码重复不可用");
        }
        //判断业务含义是否重复
        if (!checkSystemDescValid(param, id)) {
            throw new BusinessException("system_no业务含义重复不可用");
        }
        param.put("org_id", SecurityContextHolder.getOrgId());
        param.put("system_no", systemmanage.getCode());
        List<DeliverDto> dtoList = getCustomDeliverDetail(param);
        if (ObjectUtil.isNotEmpty(dtoList)) {
            List<String> deliver_code_list = dtoList.stream().map(DeliverDto::getCode).collect(Collectors.toList());
            throw new BusinessException("不能修改，问卷编号：" + deliver_code_list + "正在使用该外部参数");
        }
        systemmanageMapper.update(null, new LambdaUpdateWrapper<OpenplatformSystemmanage>()
                .eq(OpenplatformSystemmanage::getId, id)
                .set(OpenplatformSystemmanage::getCode, param.getString("code"))
                .set(OpenplatformSystemmanage::getDescription, param.getString("desc")));
        Map<String, String> map = new HashMap<>();
        map.put("id", id);
        return map;
    }

    @Override
    public OpenplatformSystemmanage getSystemManagesById(String id) {
        return systemmanageMapper.selectById(id);
    }

    @Override
    public List<OpenplatformSystemmanage> getSystemManagesList(String orgId) {
        return systemmanageMapper.selectList(new LambdaQueryWrapper<OpenplatformSystemmanage>()
                .eq(OpenplatformSystemmanage::getOrgId, orgId)
                .orderByDesc(OpenplatformSystemmanage::getCreatedDt));
    }

    @Override
    public OpenplatformSystemmanagePageVo getSystemManagesPage(Page<OpenplatformSystemmanage> page, String orgId) {
        OpenplatformSystemmanagePageVo pageVo = new OpenplatformSystemmanagePageVo();
        pageVo.setPage(page.getCurrent());
        Page<OpenplatformSystemmanage> systemmanagePage = systemmanageMapper.selectPage(page, new LambdaQueryWrapper<OpenplatformSystemmanage>()
                .eq(OpenplatformSystemmanage::getOrgId, orgId)
                .orderByDesc(OpenplatformSystemmanage::getCreatedDt));
        List<OpenplatformSystemmanage> systemmanageList = systemmanagePage.getRecords();
        if (CollUtil.isEmpty(systemmanageList)) {
            pageVo.setTotalCount(0);
            pageVo.setRows(new ArrayList<>());
            return pageVo;
        }
        //组装
        pageVo.setRows(systemmanageList);
        pageVo.setTotalCount(systemmanagePage.getTotal());
        return pageVo;
    }

    @Override
    public Map<String, Integer> deleteSystemmanages(String id) {
        OpenplatformSystemmanage systemmanage = systemmanageMapper.selectById(id);
        if (ObjectUtil.isEmpty(systemmanage)) {
            throw new BusinessException("SystemManage[id=" + id + "] not found");
        }
        JSONObject param = new JSONObject();
        param.put("org_id", SecurityContextHolder.getOrgId());
        param.put("system_no", systemmanage.getCode());
        List<DeliverDto> dtoList = getCustomDeliverDetail(param);
        if (ObjectUtil.isNotEmpty(dtoList)) {
            List<String> deliver_code_list = dtoList.stream().map(DeliverDto::getCode).collect(Collectors.toList());
            throw new BusinessException("不能删除，问卷编号：" + deliver_code_list + "正在使用该外部参数");
        }
        Integer count = systemmanageMapper.deleteById(id);
        Map<String, Integer> map = new HashMap<>();
        map.put("deletedCount", count);
        return map;
    }

    @Override
    public Map<String, String> postConditionmanages(JSONObject param) {
        checkSystemAndConditionCodeDesc(param);
        //判断系统编号是否可用
        if (!checkConditionCodeValid(param, null)) {
            throw new BusinessException("编码重复不可用");
        }
        //判断业务含义是否重复
        if (!checkConditionDescValid(param, null)) {
            throw new BusinessException("condition_no业务含义重复不可用");
        }
        //保存数据
        OpenplatformConditionmanage conditionmanage = new OpenplatformConditionmanage();
        conditionmanage.setOrgId(SecurityContextHolder.getOrgId());
        conditionmanage.setCode(param.getString("code"));
        conditionmanage.setDescription(param.getString("desc"));
        conditionmanageMapper.insert(conditionmanage);
        Map<String, String> map = new HashMap<>();
        map.put("id", conditionmanage.getId());
        return map;
    }

    @Override
    public OpenplatformConditionmanage getConditionmanagesById(String id) {
        return conditionmanageMapper.selectById(id);
    }

    @Override
    public List<OpenplatformConditionmanage> getConditionmanagesList(String orgId) {
        return conditionmanageMapper.selectList(new LambdaQueryWrapper<OpenplatformConditionmanage>()
                .eq(OpenplatformConditionmanage::getOrgId, orgId)
                .orderByDesc(OpenplatformConditionmanage::getCreatedDt));
    }

    @Override
    public OpenplatformConditionmanagesPageVo getConditionmanagesPage(Page<OpenplatformConditionmanage> page, String orgId) {
        OpenplatformConditionmanagesPageVo pageVo = new OpenplatformConditionmanagesPageVo();
        pageVo.setPage(page.getCurrent());
        Page<OpenplatformConditionmanage> conditionmanagePage = conditionmanageMapper.selectPage(page, new LambdaQueryWrapper<OpenplatformConditionmanage>()
                .eq(OpenplatformConditionmanage::getOrgId, orgId)
                .orderByDesc(OpenplatformConditionmanage::getCreatedDt));
        List<OpenplatformConditionmanage> conditionmanageList = conditionmanagePage.getRecords();
        if (CollUtil.isEmpty(conditionmanageList)) {
            pageVo.setTotalCount(0);
            pageVo.setRows(new ArrayList<>());
            return pageVo;
        }
        //组装
        pageVo.setRows(conditionmanageList);
        pageVo.setTotalCount(conditionmanagePage.getTotal());
        return pageVo;
    }

    @Override
    public Map<String, String> putConditionmanages(String id, JSONObject param) {
        OpenplatformConditionmanage conditionmanage = conditionmanageMapper.selectById(id);
        if (ObjectUtil.isEmpty(conditionmanage)) {
            throw new BusinessException("OpenplatformConditionmanage[id=" + id + "}] not found");
        }
        checkSystemAndConditionCodeDesc(param);
        //判断系统编号是否可用
        if (!checkConditionCodeValid(param, id)) {
            throw new BusinessException("编码重复不可用");
        }
        //判断业务含义是否重复
        if (!checkConditionDescValid(param, id)) {
            throw new BusinessException("system_no业务含义重复不可用");
        }
        param.put("org_id", SecurityContextHolder.getOrgId());
        param.put("condition_no", conditionmanage.getCode());
        List<DeliverDto> dtoList = getCustomDeliverDetail(param);
        if (ObjectUtil.isNotEmpty(dtoList)) {
            List<String> deliver_code_list = dtoList.stream().map(DeliverDto::getCode).collect(Collectors.toList());
            throw new BusinessException("不能修改，问卷编号：" + deliver_code_list + "正在使用该外部参数");
        }
        conditionmanageMapper.update(null, new LambdaUpdateWrapper<OpenplatformConditionmanage>()
                .eq(OpenplatformConditionmanage::getId, id)
                .set(OpenplatformConditionmanage::getCode, param.getString("code"))
                .set(OpenplatformConditionmanage::getDescription, param.getString("desc")));
        Map<String, String> map = new HashMap<>();
        map.put("id", id);
        return map;
    }

    @Override
    public Map<String, Integer> deleteConditionmanages(String id) {
        OpenplatformConditionmanage conditionmanage = conditionmanageMapper.selectById(id);
        if (ObjectUtil.isEmpty(conditionmanage)) {
            throw new BusinessException("OpenplatformConditionmanage[id=" + id + "] not found");
        }
        JSONObject param = new JSONObject();
        param.put("org_id", SecurityContextHolder.getOrgId());
        param.put("condition_no", conditionmanage.getCode());
        List<DeliverDto> dtoList = getCustomDeliverDetail(param);
        if (ObjectUtil.isNotEmpty(dtoList)) {
            List<String> deliver_code_list = dtoList.stream().map(DeliverDto::getCode).collect(Collectors.toList());
            throw new BusinessException("不能删除，问卷编号：" + deliver_code_list + "正在使用该外部参数");
        }
        Integer count = conditionmanageMapper.deleteById(id);
        Map<String, Integer> map = new HashMap<>();
        map.put("deletedCount", count);
        return map;
    }

    @Override
    public List<OpenplatformExtparam> postExtparam(JSONObject param) {
        List<OpenplatformExtparam> extparamList = new ArrayList<>();
        if (ObjectUtil.isEmpty(param.getJSONArray("name"))) {
            return extparamList;
        }
        return openplatformExtparamMapper.selectList(new LambdaQueryWrapper<OpenplatformExtparam>()
                .eq(OpenplatformExtparam::getOrgId, SecurityContextHolder.getOrgId())
                .in(OpenplatformExtparam::getName, param.getJSONArray("name"))
                .eq(OpenplatformExtparam::getStatus, EXTPARAM_STATUS_START.getNumber()));
    }

    @Override
    public List<OpenplatformExtparamenummanage> postExtparamenum(JSONObject param) {
        List<OpenplatformExtparamenummanage> extparamenummanageList = new ArrayList<>();
        if (ObjectUtil.isEmpty(param.getJSONArray("ext_param_id_list"))) {
            return extparamenummanageList;
        }
        return extparamenummanageMapper.selectList(new LambdaQueryWrapper<OpenplatformExtparamenummanage>()
                .eq(OpenplatformExtparamenummanage::getOrgId, SecurityContextHolder.getOrgId())
                .eq(OpenplatformExtparamenummanage::getStatus, EXTPARAMENUMMANAGE_STATUS_START.getNumber())
                .in(OpenplatformExtparamenummanage::getExtParamId, param.getJSONArray("ext_param_id_list")));
    }

    @Override
    public Map<String, Object> getSystemconditionCheck(HttpServletRequest request) {
        String system_no = request.getParameter("system_no");
        String condition_no = request.getParameter("condition_no");
        String org_id = SecurityContextHolder.getOrgId();
        log.info("--------1-------" + org_id);
        JSONObject params = new JSONObject();
        params.put("org_id", org_id);
        Map<String, Object> data = new HashMap<>();
        data.put("condition_list", new ArrayList<>());
        data.put("system_list", new ArrayList<>());
        //如果system_no传过来
        if (ObjectUtil.isNotEmpty(system_no)) {
            params.put("system_no", system_no);
            List<OpenplatformConditionmanageVo> conditionmanageVos = new ArrayList<>();
            //查询订制投放配置
            List<DeliverExtDeliverMappingDto> custom_deliver_list = deliverGrpcClient.listExtDeliverMapping(params);
            //查询所有条件
            List<OpenplatformConditionmanage> condition_list = conditionmanageMapper.selectList(new LambdaQueryWrapper<OpenplatformConditionmanage>()
                    .eq(OpenplatformConditionmanage::getOrgId, org_id));
            if (ObjectUtil.isNotEmpty(custom_deliver_list)) {
                List<String> exist_condition_no_list = custom_deliver_list.stream().map(DeliverExtDeliverMappingDto::getConditionNo).collect(Collectors.toList());
                for (OpenplatformConditionmanage conditionmanage : condition_list) {
                    OpenplatformConditionmanageVo conditionmanageVo = new OpenplatformConditionmanageVo();
                    BeanUtil.copyProperties(conditionmanage, conditionmanageVo);
                    if (exist_condition_no_list.contains(conditionmanage.getCode())) {
                        conditionmanageVo.set_custom(true);
                    } else {
                        conditionmanageVo.set_custom(false);
                    }
                    conditionmanageVos.add(conditionmanageVo);
                }
            } else {
                for (OpenplatformConditionmanage conditionmanage : condition_list) {
                    OpenplatformConditionmanageVo conditionmanageVo = new OpenplatformConditionmanageVo();
                    BeanUtil.copyProperties(conditionmanage, conditionmanageVo);
                    conditionmanageVo.set_custom(false);
                    conditionmanageVos.add(conditionmanageVo);
                }
            }
            data.put("condition_list", conditionmanageVos);
            params.remove("system_no");
        } else if (ObjectUtil.isNotEmpty(condition_no)) {
            params.put("condition_no", condition_no);
            List<OpenplatformSystemmanageVo> systemmanageVos = new ArrayList<>();
            //查询订制投放配置
            List<DeliverExtDeliverMappingDto> custom_deliver_list = deliverGrpcClient.listExtDeliverMapping(params);
            //查询所有条件
            List<OpenplatformSystemmanage> system_list = systemmanageMapper.selectList(new LambdaQueryWrapper<OpenplatformSystemmanage>()
                    .eq(OpenplatformSystemmanage::getOrgId, org_id));
            if (ObjectUtil.isNotEmpty(custom_deliver_list)) {
                List<String> exist_code_list = custom_deliver_list.stream().map(DeliverExtDeliverMappingDto::getConditionNo).collect(Collectors.toList());
                for (OpenplatformSystemmanage systemmanage : system_list) {
                    OpenplatformSystemmanageVo systemmanageVo = new OpenplatformSystemmanageVo();
                    BeanUtil.copyProperties(systemmanage, systemmanageVo);
                    if (exist_code_list.contains(systemmanage.getCode())) {
                        systemmanageVo.set_custom(true);
                    } else {
                        systemmanageVo.set_custom(false);
                    }
                    systemmanageVos.add(systemmanageVo);
                }
            } else {
                for (OpenplatformSystemmanage systemmanage : system_list) {
                    OpenplatformSystemmanageVo systemmanageVo = new OpenplatformSystemmanageVo();
                    BeanUtil.copyProperties(systemmanage, systemmanageVo);
                    systemmanageVo.set_custom(false);
                    systemmanageVos.add(systemmanageVo);
                }
            }
            data.put("system_list", systemmanageVos);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("data", data);
        return result;
    }

    @Override
    public OpenplatformFunctionoption getFunctionoptionsById(String id) {
        OpenplatformFunctionoption functionoption = functionoptionMapper.selectById(id);
        if (ObjectUtil.isEmpty(functionoption)) {
            throw new BusinessException("OpenplatformFunctionoption[id=" + id + "] not found");
        }
        return functionoption;
    }

    @Override
    public List<OpenplatformFunctionoption> getFunctionoptionsList(HttpServletRequest request) {
        String orgId = SecurityContextHolder.getOrgId();
        return functionoptionMapper.selectList(new LambdaQueryWrapper<OpenplatformFunctionoption>()
                .eq(OpenplatformFunctionoption::getOrgId, orgId));
    }

    @Override
    public OpenplatformFunctionoptionsPageVo getFunctionoptionsPage(Page<OpenplatformFunctionoption> page, HttpServletRequest request) {
        String orgId = SecurityContextHolder.getOrgId();
        OpenplatformFunctionoptionsPageVo pageVo = new OpenplatformFunctionoptionsPageVo();
        pageVo.setPage(page.getCurrent());
        Page<OpenplatformFunctionoption> functionoptionPage = functionoptionMapper.selectPage(page,
                new LambdaQueryWrapper<OpenplatformFunctionoption>().eq(OpenplatformFunctionoption::getOrgId, orgId));
        List<OpenplatformFunctionoption> functionoptions = functionoptionPage.getRecords();
        if (CollUtil.isEmpty(functionoptions)) {
            pageVo.setTotalCount(0);
            pageVo.setRows(new ArrayList<>());
            return pageVo;
        }
        //组装
        pageVo.setRows(functionoptions);
        pageVo.setTotalCount(functionoptionPage.getTotal());
        return pageVo;
    }

    private boolean checkExtParamsNameFormat(String str) {
        return str.length() <= 16 && !str.startsWith("xm_") && str.matches("^[a-zA-Z0-9_]+$");
    }

    private boolean checkExtParamsNameValid(String str) {
        String orgId = SecurityContextHolder.getOrgId();
        return openplatformExtparamMapper.exists(new LambdaQueryWrapper<OpenplatformExtparam>()
                .eq(OpenplatformExtparam::getOrgId, orgId)
                .eq(OpenplatformExtparam::getName, str)
                .eq(OpenplatformExtparam::getStatus, EXTPARAM_STATUS_START.getNumber()));
    }

    private boolean checkExtParamsNameValidPutMethod(String extparamId, String str) {
        boolean flag = false;
        String orgId = SecurityContextHolder.getOrgId();
        OpenplatformExtparam openplatformExtparam = openplatformExtparamMapper.selectOne(new LambdaQueryWrapper<OpenplatformExtparam>()
                .eq(OpenplatformExtparam::getOrgId, orgId)
                .eq(OpenplatformExtparam::getName, str)
                .eq(OpenplatformExtparam::getStatus, EXTPARAM_STATUS_START.getNumber()));
        if (ObjectUtil.isEmpty(openplatformExtparam)) {
            flag = true;
        } else if (extparamId.equals(openplatformExtparam.getId())) {
            flag = true;
        }
        return flag;
    }

    private boolean checkExtParamsNumByOrgId() {
        boolean flag = true;
        String orgId = SecurityContextHolder.getOrgId();
        Long count = openplatformExtparamMapper.selectCount(new LambdaQueryWrapper<OpenplatformExtparam>()
                .eq(OpenplatformExtparam::getOrgId, orgId)
                .eq(OpenplatformExtparam::getStatus, EXTPARAM_STATUS_START.getNumber()));
        if (count >= 100) {
            flag = false;
        }
        return flag;
    }

    private boolean checkExtParamsDescValid(String str) {
        String orgId = SecurityContextHolder.getOrgId();
        return openplatformExtparamMapper.exists(new LambdaQueryWrapper<OpenplatformExtparam>()
                .eq(OpenplatformExtparam::getOrgId, orgId)
                .eq(OpenplatformExtparam::getDescription, str)
                .eq(OpenplatformExtparam::getStatus, EXTPARAM_STATUS_START.getNumber()));
    }

    private boolean checkExtParamsDescValidPutMethod(String extparamId, String str) {
        boolean flag = false;
        String orgId = SecurityContextHolder.getOrgId();
        OpenplatformExtparam openplatformExtparam = openplatformExtparamMapper.selectOne(new LambdaQueryWrapper<OpenplatformExtparam>()
                .eq(OpenplatformExtparam::getOrgId, orgId)
                .eq(OpenplatformExtparam::getDescription, str)
                .eq(OpenplatformExtparam::getStatus, EXTPARAM_STATUS_START.getNumber()));
        if (ObjectUtil.isEmpty(openplatformExtparam)) {
            flag = true;
        } else if (extparamId.equals(openplatformExtparam.getId())) {
            flag = true;
        }
        return flag;
    }

    private boolean checkExtParamsDescFormat(String str) {
        boolean flag = true;
        String regex = "^[\\u4e00-\\u9fa5a-zA-Z0-9]+$";//只能是汉字、英文字母，数字组合
        if (str.length() > 8 || !Pattern.matches(regex, str)) {
            flag = false;
        }
        return flag;
    }

    private void updateExtparam(String id, JSONObject param) {
        openplatformExtparamMapper.update(null, new LambdaUpdateWrapper<OpenplatformExtparam>()
                .eq(OpenplatformExtparam::getId, id)
                .set(OpenplatformExtparam::getUpdatedDt, LocalDateTime.now())
                .set(OpenplatformExtparam::getName, param.getString("name"))
                .set(OpenplatformExtparam::getDtype, param.getInteger("dtype"))
                .set(OpenplatformExtparam::getDescription, param.getString("desc"))
                .set(OpenplatformExtparam::getStatus, param.getInteger("status")));
    }

    private List<DeliverDto> getDeliverExtParamsDetail(JSONObject query) {
        List<DeliverDto> result = new ArrayList<>();
        List<DeliverExtParamsDto> deliver_list = deliverGrpcClient.listDeliverExtparams(query);
        if (ObjectUtil.isEmpty(deliver_list)) {
            return result;
        }
        List<String> ids = deliver_list.stream().map(DeliverExtParamsDto::getDeliverId).collect(Collectors.toList());
        List<DeliverDto> deliverList = deliverGrpcClient.listDeliverByIds(ids);
        deliverList.forEach(a -> {
            if (a.getStatus() != DELIVER_STATUS_DELETE.getNumber() && a.getStatus() != DELIVER_STATUS_FINISH.getNumber()) {
                result.add(a);
            }
        });
        return result;
    }

    private List<Object> getSurveyExtParamsDetail(String orgId, String extParamId) {
        List<Object> objects = new ArrayList<>();
        List<QdesProjectDto> qdesProjectDtos = qdesGrpcClient.listProject(orgId);
        if (ObjectUtil.isEmpty(qdesProjectDtos)) {
            return objects;
        }
        qdesProjectDtos.forEach(a -> {
            List<Integer> versions = new ArrayList<>();
            if (a.getVersion() != null) {
                versions.add(a.getVersion());
            }
            if (a.getReleaseVer() != null) {
                versions.add(a.getReleaseVer());
            }
            if (ObjectUtil.isNotEmpty(versions)) {
                List<QstructsDto> qstructsDtos = qdesGrpcClient.listQStruct(a.getId(), versions);
                qstructsDtos.forEach(b -> {
                    if (ObjectUtil.isNotEmpty(JSONObject.parseObject(b.getData()).get("ext_params"))) {
                        if (JSONObject.parseObject(b.getData()).getJSONObject("ext_params").containsKey(extParamId)) {
                            objects.add(a.getTitle());
                        }
                    }
                });
            }
        });
        return objects;
    }

    private void checkSystemAndConditionCodeDesc(JSONObject param) {
        if (ObjectUtil.isEmpty(param.getString("code"))) {
            throw new BusinessException("缺少编码参数");
        }
        if (!checkCodeFormat(param.getString("code"))) {
            throw new BusinessException("编码只能输入数字字母下划线，最多10个字符");
        }
        if (ObjectUtil.isEmpty(param.getString("desc"))) {
            throw new BusinessException("缺少业务含义参数");
        }
        if (param.getString("desc").length() > 20) {
            throw new BusinessException("业务含义最多20个字符");
        }

    }

    private boolean checkCodeFormat(String str) {
        return str.length() <= 10 && str.matches("^[a-zA-Z0-9_]+$");
    }

    private boolean checkSystemCodeVlid(JSONObject param, String id) {
        List<OpenplatformSystemmanage> system_list = systemmanageMapper.selectList(
                new LambdaQueryWrapper<OpenplatformSystemmanage>()
                        .eq(OpenplatformSystemmanage::getCode, param.getString("code"))
                        .eq(OpenplatformSystemmanage::getOrgId, SecurityContextHolder.getOrgId()));
        if (ObjectUtil.isEmpty(system_list)) {
            return true;
        }
        //如果是put请求
        return StrUtil.isNotBlank(id) && id.equals(system_list.get(0).getId());
    }

    private boolean checkConditionCodeValid(JSONObject param, String id) {
        List<OpenplatformConditionmanage> condition_list = conditionmanageMapper.selectList(
                new LambdaQueryWrapper<OpenplatformConditionmanage>()
                        .eq(OpenplatformConditionmanage::getCode, param.getString("code"))
                        .eq(OpenplatformConditionmanage::getOrgId, SecurityContextHolder.getOrgId()));
        if (ObjectUtil.isEmpty(condition_list)) {
            return true;
        }
        //如果是put请求
        return StrUtil.isNotBlank(id) && id.equals(condition_list.get(0).getId());
    }

    private boolean checkSystemDescValid(JSONObject param, String id) {
        List<OpenplatformSystemmanage> system_list = systemmanageMapper.selectList(
                new LambdaQueryWrapper<OpenplatformSystemmanage>()
                        .eq(OpenplatformSystemmanage::getDescription, param.getString("desc"))
                        .eq(OpenplatformSystemmanage::getOrgId, SecurityContextHolder.getOrgId()));
        if (ObjectUtil.isEmpty(system_list)) {
            return true;
        }
        //如果是put请求
        return StrUtil.isNotBlank(id) && id.equals(system_list.get(0).getId());
    }

    private boolean checkConditionDescValid(JSONObject param, String id) {
        List<OpenplatformConditionmanage> condition_list = conditionmanageMapper.selectList(
                new LambdaQueryWrapper<OpenplatformConditionmanage>()
                        .eq(OpenplatformConditionmanage::getDescription, param.getString("desc"))
                        .eq(OpenplatformConditionmanage::getOrgId, SecurityContextHolder.getOrgId()));
        if (ObjectUtil.isEmpty(condition_list)) {
            return true;
        }
        //如果是put请求
        return StrUtil.isNotBlank(id) && id.equals(condition_list.get(0).getId());
    }

    private boolean checkSystemDescValidPut(JSONObject param, String id) {
        List<OpenplatformSystemmanage> system_list = systemmanageMapper.selectList(
                new LambdaQueryWrapper<OpenplatformSystemmanage>()
                        .eq(OpenplatformSystemmanage::getDescription, param.getString("desc"))
                        .eq(OpenplatformSystemmanage::getOrgId, SecurityContextHolder.getOrgId()));
        if (ObjectUtil.isEmpty(system_list)) {
            return true;
        } else if (system_list.get(0).getId().equals(id)) {
            return true;
        }
        return false;
    }

    private List<DeliverDto> getCustomDeliverDetail(JSONObject param) {
        List<DeliverDto> result = new ArrayList<>();
        List<DeliverExtDeliverMappingDto> extDeliverMappingDtos = deliverGrpcClient.listExtDeliverMapping(param);
        if (ObjectUtil.isEmpty(extDeliverMappingDtos)) {
            return result;
        }
        List<String> ids = extDeliverMappingDtos.stream().map(DeliverExtDeliverMappingDto::getDeliverId).collect(Collectors.toList());
        List<DeliverDto> deliverList = deliverGrpcClient.listDeliverByIds(ids);
        deliverList.forEach(a -> {
            if (a.getStatus() != DELIVER_STATUS_DELETE.getNumber() && a.getStatus() != DELIVER_STATUS_FINISH.getNumber()) {
                result.add(a);
            }
        });
        return result;
    }

    public void initOrgAesKey() {
        log.info("外部参数加密配置表");
        List<OpenplatformEncryptionconfig> encryptionconfigList = encryptionconfigMapper.selectList(
                new LambdaQueryWrapper<OpenplatformEncryptionconfig>()
                        .eq(OpenplatformEncryptionconfig::getOrgId, SecurityContextHolder.getOrgId())
                        .eq(OpenplatformEncryptionconfig::getEType, ENCRYPTIONCONFIG_E_TYPE_AES.getNumber()));
        if (ObjectUtil.isEmpty(encryptionconfigList)) {
            OpenplatformEncryptionconfig encryptionconfig = new OpenplatformEncryptionconfig();
            JSONObject aesConfig = new JSONObject();
            aesConfig.put("aes_key", RandomStringUtils.randomAscii(16));
            encryptionconfig.setOrgId(SecurityContextHolder.getOrgId());
            encryptionconfig.setEType(ENCRYPTIONCONFIG_E_TYPE_AES.getNumber());
            encryptionconfig.setAesConfig(String.valueOf(aesConfig));
            encryptionconfigMapper.insert(encryptionconfig);
        }
    }
}
